package com.shchuangzhi.smartguard;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;

import com.elvishew.xlog.XLog;
import com.shchuangzhi.smartguard.core.CheckInOutResult;
import com.shchuangzhi.smartguard.core.Consts;
import com.shchuangzhi.smartguard.core.DBHelper;
import com.shchuangzhi.smartguard.core.Job;
import com.shchuangzhi.smartguard.core.JobManager;
import com.shchuangzhi.smartguard.core.Machine;
import com.shchuangzhi.smartguard.core.Mode;
import com.shchuangzhi.smartguard.core.Notify;
import com.shchuangzhi.smartguard.core.NotifyMessage;
import com.shchuangzhi.smartguard.core.NotifyPrinter;
import com.shchuangzhi.smartguard.core.Swiper;
import com.shchuangzhi.smartguard.core.TTS;
import com.shchuangzhi.smartguard.core.command.Command;
import com.shchuangzhi.smartguard.fragment.Event;
import com.shchuangzhi.smartguard.fragment.FragmentNamed;
import com.shchuangzhi.smartguard.fragment.Receiver;
import com.shchuangzhi.smartguard.fragment.Settings;
import com.shchuangzhi.smartguard.fragment.Stats;
import com.shchuangzhi.smartguard.fragment.Terminal;

public class MainActivity extends AppCompatActivity {

    private DBHelper dbHelper;
    private TitleBar titleBar;
    private StringBuilder sb = new StringBuilder();
    private FragmentNamed current;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                NotifyMessage message = (NotifyMessage) msg.obj;
                titleBar.loadTitle((String)message.getData());
            } catch(Exception e) {
                XLog.e("", e);
            }
        }
    };

    private Handler receiverStatsChangedHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                titleBar.loadReceiverTitle();
            } catch(Exception e) {
                XLog.e("", e);
            }
        }
    };

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_terminal:
                    switchFragment(Consts.TERMINAL_FRAGMENT_NAME, R.id.navigation_terminal);
                    return true;
                case R.id.navigation_stats:
                    switchFragment(Consts.STATS_FRAGMENT_NAME, R.id.navigation_stats);
                    return true;
                case R.id.navigation_settings:
                    switchFragment(Consts.SETTINGS_FRAGMENT_NAME, R.id.navigation_settings);
                    return true;
                case R.id.navigation_event:
                    switchFragment(Consts.EVENT_FRAGMENT_NAME, R.id.navigation_event);
                    return true;
                case R.id.navigation_receiver:
                    switchFragment(Consts.RECEIVER_FRAGMENT_NAME, R.id.navigation_receiver);
                    return true;
            }
            return false;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        dbHelper = new DBHelper(this);
        SharedPref.getInstance().init(this);
        Mode.getInstance().init(SharedPref.getInstance().getPreferences());
        Machine.getInstance().init();
        TTS.init(this);

        setContentView(R.layout.activity_main);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getSupportActionBar().hide();

        JobManager.resumeAll();

        titleBar = new TitleBar(this, dbHelper).init();

        Command command = (Command)JobManager.get(Consts.JOB_NETWORK_CHECK).getData();

        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        if (Machine.getInstance().getType() == Machine.MachineType.Gate) {
            navigation.getMenu().removeItem(R.id.navigation_receiver);
            current = newFragment(R.id.navigation_terminal);
            Job dataSyncJob = JobManager.get(Consts.JOB_DATA_SYNC);
            command = (Command)dataSyncJob.getData();
            command.setDBHelper(new DBHelper(this));
            command.setNotifier(dataSyncJob);

            Job receiverDataSyncJob = JobManager.get(Consts.JOB_RECEIVER_DATA_SYNC);
            receiverDataSyncJob.suspend();

            NotifyPrinter.getInstance().addNotify(Consts.NOTIFY_SCHOOL_CHANGED, new Notify() {
                @Override
                public void notify(NotifyMessage message) {
                    handler.sendMessage(handler.obtainMessage(Consts.NOTIFY_SCHOOL_CHANGED, message));
                }
            });
            NotifyPrinter.getInstance().notify(NotifyMessage.wrap("",  Consts.NOTIFY_SCHOOL_CHANGED));
            findViewById(R.id.receiver_stats).setVisibility(View.INVISIBLE);
        } else {
            Job dataSyncJob = JobManager.get(Consts.JOB_DATA_SYNC);
            dataSyncJob.suspend();

            navigation.getMenu().removeItem(R.id.navigation_terminal);
            navigation.getMenu().removeItem(R.id.navigation_stats);
            current = newFragment(R.id.navigation_receiver);
            findViewById(R.id.receiver_stats).setVisibility(View.VISIBLE);
            NotifyPrinter.getInstance().addNotify(Consts.NOTIFY_RECEIVER_STATS_CHANGED, new Notify() {
                @Override
                public void notify(NotifyMessage message) {
                    receiverStatsChangedHandler.sendMessage(handler.obtainMessage(Consts.NOTIFY_RECEIVER_STATS_CHANGED, message));
                }
            });
        }

        FragmentTransaction tx = getFragmentManager().beginTransaction();
        tx.replace(R.id.content, current.Fragment(), current.Name());
        tx.commit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertDialog dialog = new AlertDialog.Builder(this).create();
            dialog.setTitle(Consts.SYSTEM_INFO);
            dialog.setMessage(Consts.CONFIRM_EXIT);
            dialog.setButton(DialogInterface.BUTTON_POSITIVE, Consts.POSITIVE_BUTTON, listener);
            dialog.setButton(DialogInterface.BUTTON_NEGATIVE, Consts.NEGATIVE_BUTTON, listener);
            dialog.show();
        }
//        else if (keyCode == KeyEvent.KEYCODE_ENTER) {
//            String cardNo = sb.toString().replaceFirst("^0*", "");
//            sb = new StringBuilder();
//            if (!cardNo.equals("")) {
//                Swiper swiper = dbHelper.getSwiperByCard(cardNo);
//                if (swiper != null) {
//                    CheckInOutResult result = swiper.swipe(Mode.getInstance().getCurrent());
//                    if (!result.isOk()) {
//                        TTS.get().speak(result.getVoice());
//                    }
//                } else {
//                    TTS.get().speak(Consts.SPEECH_INVALID);
//                    NotifyPrinter.getInstance().notify(
//                            NotifyMessage.info(String.format("%s:%s:1",
//                                    Consts.SPEECH_INVALID, cardNo), Consts.NOTIFY_DATA_SYNC, Consts.NOTIFY_DATA_SYC_VIEW_LIST));
//                }
//            }
//        } else {
//            if (sb.length() >= 15) {
//                sb = new StringBuilder();
//            }
//            sb.append(keyCode - 7);
//        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        JobManager.suspendAll();
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
    }


    private void switchFragment(String name, int fragmentId) {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        FragmentNamed found = (FragmentNamed)fm.findFragmentByTag(name);
        if (current != null) {
            if (current.Name() != name) {
                tx.hide(current.Fragment());
                if (found != null) {
                    current = found;
                    tx.show(current.Fragment());
                } else {
                    current = newFragment(fragmentId);
                    tx.add(R.id.content, current.Fragment(), current.Name());
                }
            }
        } else {
            current = newFragment(fragmentId);
            tx.add(R.id.content, current.Fragment(), current.Name());
        }
        tx.commit();
    }

    private FragmentNamed newFragment(int fragmentId) {
        switch(fragmentId) {
            case R.id.navigation_terminal:return new Terminal();
            case R.id.navigation_stats:return new Stats();
            case R.id.navigation_settings:return new Settings();
            case R.id.navigation_event:return new Event();
            case R.id.navigation_receiver:return new Receiver();
        }
        return null;
    }


    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int which)
        {
            switch (which)
            {
                case AlertDialog.BUTTON_POSITIVE:
                    finish();
                    break;
                case AlertDialog.BUTTON_NEGATIVE:
                    break;
                default:
                    break;
            }
        }
    };
}
